<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleDialogClose"
    :close-on-click-modal="false"
    :class="{'mobile-el-dialog':showMobilePage}"
    modal-append-to-body
    lock-scroll
    class="subcribe-common-dialog normal-common-dialog-size"
  >
    <div class="create-info-box">
      <DialogTitle :title="isEdit ? '库存编辑' : '添加入库'" font-size="16px" style="margin-bottom: 16px" />
      <el-form
        ref="stockOperationForm"
        :model="stockForm"
        :rules="formRules"
        :label-position="showMobilePage?'left':'right'"
        class="lineHeight32"
        label-width="110px">
        <el-row :class="{'mobile-subcribe-dialog': showMobilePage}" :style="!showMobilePage?'':{maxHeight: maxHeight}" class="response-el-row" type="flex">
          <el-col :span="labelSpan">
            <el-form-item label="SKU编码：" prop="code">
              <selectWithUserLoad
                ref="resourceNameRef"
                v-model="stockForm.code"
                :loadmore-method="querySkuList()"
                :hide-select-list="[]"
                :extend-params="{ deduplication: 1 }"
                :disabled="isLock"
                key-name="crmCode"
                label-name="crmCode"
                filterable
                clearable
                @changeMethod="queryInventoryRepo"/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="仓库：" prop="repositoryId">
              <el-select :disabled="!stockForm.code || isLock" v-model="stockForm.repositoryId" popper-class="global-select-down">
                <el-option
                  v-if="selectedRepository.repositoryId"
                  :label="selectedRepository.repositoryName"
                  :value="selectedRepository.repositoryId" />
                <el-option
                  v-for="repository in repositoryList"
                  :key="repository.repositoryId"
                  :label="repository.repositoryName"
                  :value="repository.repositoryId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="成本价(元)：" prop="cost">
              <el-input
                v-model="stockForm.cost"
                :disabled="isLock"
                :oninput="`
                  if(value>999999999) {value=999999999}
                  else if(value < 0) {value = null}
                `"
                placeholder="请输入"
                type="text"
                maxlength="15"
                @change="numberInputChange('cost')"/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="包含物流成本：" prop="hasLogisticsCost">
              <el-radio-group v-model="stockForm.hasLogisticsCost" :disabled="isLock">
                <el-radio :label="1"><span style="font-size:14px;">是</span></el-radio>
                <el-radio :label="0"><span style="font-size:14px;">否</span></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="入库数量：" prop="inventoryCount">
              <el-input
                v-model="stockForm.inventoryCount"
                :disabled="isLock"
                placeholder="请输入"
                type="text"
                maxlength="7"
                @input="valToPureNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="物流成本(元)：" prop="logisticsCost">
              <el-input
                v-model="stockForm.logisticsCost"
                :oninput="`
                  if(value>999999999) {value=999999999}
                  else if(value < 0) {value = null}
                `"
                placeholder="请输入"
                type="text"
                maxlength="15"
                @change="numberInputChange('logisticsCost')"/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="入库类型：" prop="stockInType">
              <el-select v-model="stockForm.stockInType" :disabled="isLock" popper-class="global-select-down">
                <el-option
                  v-for="item in stockInTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="供应商：" prop="supplierId">
              <selectWithUserLoad
                v-model="stockForm.supplierId"
                :loadmore-method="querySupplierList()"
                :default-list="selectedSupplier"
                :disabled="isLock"
                placeholder="请选择"
                key-name="id"
                label-name="keyword"
                clearable
                filterable/>
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="入库时间：" prop="inventoryTime">
              <el-date-picker
                v-model="stockForm.inventoryTime"
                :disabled="isLock"
                :picker-options="pickerOptions"
                type="datetime"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="labelSpan">
            <el-form-item label="备注：" prop="remark">
              <el-input
                :autosize="{minRows: 2, maxRows: 3}"
                v-model="stockForm.remark"
                placeholder="请输入"
                resize="none"
                name="remark"
                type="textarea"
                maxlength="500"
                class="remark-input"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button :disabled="fetchLoading" class="ok" type="primary" @click="formValidate">{{ isEdit ? '保存' : '确定' }}</el-button>
      <el-button class="cancel-btn-style" type="info" @click="handleDialogClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DialogTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getMengliSuppliers } from '@/api/mengliOrder';
import { addInventory, editInventoryLog, getInventoryRepo, getSkuList, getStockInTypeList } from '@/api/mengli';
import { mapState } from 'vuex';

export default {
  components: {
    DialogTitle,
    selectWithUserLoad
  },
  props: {},
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      stockForm: {
        code: '',
        repositoryId: null,
        cost: null,
        hasLogisticsCost: 0,
        inventoryCount: null,
        logisticsCost: null,
        stockInType: null,
        supplierId: null,
        inventoryTime: null,
        remark: ''
      },
      fetchLoading: false,
      isLock: false,
      selectedSupplier: [], // 已选中的供应商
      selectedRepository: {}, // 已选中的仓库
      repositoryList: [],
      stockInTypes: [],
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    formRules() {
      return {
        code: [{ required: true, trigger: 'change', message: '请选择SKU编码' }],
        repositoryId: [{ required: true, trigger: 'change', message: '请选择仓库' }],
        cost: [{ required: true, trigger: 'blur', message: '请输入成本价' }],
        inventoryCount: [{ required: true, trigger: 'blur', message: '请输入入库数量' }],
        stockInType: [{ required: true, trigger: 'change', message: '请选择入库类型' }],
        inventoryTime: [{ required: true, trigger: 'change', message: '请选择入库时间' }],
        supplierId: [{ required: true, trigger: 'change', message: '请选择供应商' }]
      };
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const deadline = new Date(year, month - 1, 1, 0, 0, 0);
          return time.getTime() < deadline.getTime();
        }
      };
    },
    labelSpan() {
      return this.showMobilePage ? 24 : 12;
    }
  },
  watch: {
    dialogVisible(val) {
      val && this.queryStockInTypes();
    }
  },
  methods: {
    initDialog(rowData) {
      this.dialogVisible = true;
      this.isEdit = !!rowData;
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 3) / 5) + 'px';
      if (rowData) {
        const data = _.cloneDeep(rowData);
        this.isLock = !!data.isLock; // 已锁定的入库单只允许修改物流成本和备注
        this.selectedSupplier = [{ id: data.supplierId, keyword: data.supplier }];
        this.selectedRepository = { repositoryId: data.repositoryId, repositoryName: data.repositoryName };
        this.queryInventoryRepo({ crmCode: data.code });
        this.$nextTick(() => {
          this.stockForm = data;
          this.stockForm.stockInType = data.stockType;
          this.stockForm.inventoryTime = data.inventoryTime && data.inventoryTime * 1000;
        });
      }
    },
    // sku编码
    querySkuList() {
      return function(params) {
        return new Promise((resolve, reject) => {
          getSkuList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
    },
    // 仓库
    queryInventoryRepo(codeData) {
      if (!codeData) {
        this.$set(this.stockForm, 'repositoryId', null);
        this.repositoryList = [];
        this.selectedRepository = {};
      } else {
        const params = { page: 1, perPage: 999, code: codeData.crmCode };
        getInventoryRepo(params).then(res => {
          this.repositoryList = res.data && res.data.items || [];
          if (this.selectedRepository.repositoryId) {
            const index = this.repositoryList.findIndex(item => item.repositoryId === this.selectedRepository.repositoryId);
            index !== -1 && this.repositoryList.splice(index, 1);
          }
        });
      }
    },
    // 入库类型
    queryStockInTypes() {
      getStockInTypeList().then(res => {
        this.stockInTypes = res.data;
      });
    },
    // 供应商
    querySupplierList() {
      return function(params) {
        return new Promise((resolve, reject) => {
          getMengliSuppliers(params).then(res => {
            res.data && res.data.items.forEach(i => {
              i.keyword = i.supplier;
            });
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
    },
    numberInputChange(key) {
      if (this.stockForm[key]) {
        const valToNum = Number(this.stockForm[key]);
        this.stockForm[key] = isNaN(valToNum) ? null : valToNum.toFixed(2);
      }
    },
    valToPureNum(val) {
      if (val) {
        val = val.replace(/[^\d]/g, '');
        val = val.replace(/^0[^]+/g, '');
      }
      val = Number(val) > 9999999 ? 9999999 : Number(val) === 0 ? '' : val;
      this.$set(this.stockForm, 'inventoryCount', val);
    },
    handleDialogClose() {
      this.selectedSupplier = [];
      this.selectedRepository = {};
      this.isLock = false;
      this.$refs['stockOperationForm'].resetFields();
      this.$nextTick(() => {
        this.dialogVisible = false;
      });
    },
    formValidate() {
      this.$refs['stockOperationForm'].validate(valid => {
        if (valid) {
          this.isEdit ? this.editInventory() : this.addInventory();
        }
      });
    },
    // 提交
    addInventory() {
      this.fetchLoading = true;
      addInventory(this.stockForm).then(res => {
        this.fetchLoading = false;
        this.$message.success('添加成功');
        this.handleDialogClose();
        this.$emit('successCallback');
      }).catch(_ => {
        this.fetchLoading = false;
      });
    },
    // 修改
    editInventory() {
      this.fetchLoading = true;
      editInventoryLog(this.stockForm).then(res => {
        this.fetchLoading = false;
        this.$message.success('修改成功');
        this.handleDialogClose();
        this.$emit('successCallback');
      }).catch(_ => {
        this.fetchLoading = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 240px;
}
::v-deep .el-form-item__label {
  padding-right: 5px !important;
}
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-date-editor, .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
  }

  &.mobile-subcribe-dialog {
    @include scrollBar($x: hidden, $y: auto);
    .remark-input {
      width: 190px !important;
    }
    &::v-deep {
      .el-input, .el-select {
         width: 190px !important;
      }
      .el-input__inner {
        width: 190px;
      }
      .el-date-editor, .el-form-item__content {
        width: 190px;
      }
    }
  }
}
.create-info-box {
  margin-bottom: 8px;
  .remark-input {
    width: 240px;
    word-break: break-word;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .ok {
    width: 120px;
    font-size: 16px;
    padding: 8px 20px;
  }
  .cancel-btn-style {
    font-size: 14px;
    padding: 8px 20px;
    margin-left: 16px !important;
  }
}
</style>
